"""
权限控制器
处理权限相关的HTTP请求
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, Query, Path, status
from fastapi.responses import JSONResponse

from pkg.common.utils.response.response import ApiResponse
from pkg.common.constants.response import ResponseCode, ResponseMessage
from apps.auth.schemas.permission_schema import (
    PermissionCreate, PermissionUpdate, PermissionWholeUpdate, 
    PermissionResponse, PermissionListResponse
)
from apps.auth.services.permission_service import PermissionService
from apps.auth.models.permission import Permission


# 创建路由器实例
router = APIRouter(prefix="/permissions", tags=["权限管理"])


@router.post("", summary="创建权限")
async def create_permission(permission_data: PermissionCreate):
    """
    创建一个新权限
    
    Args:
        permission_data: 权限创建数据
        
    Returns:
        包含新创建权限信息的响应
    """
    permission = await PermissionService.create_permission(permission_data.model_dump())
    return ApiResponse.success(
        data=PermissionResponse.model_validate(permission),
        msg="权限创建成功"
    )


@router.get("", summary="获取权限列表")
async def list_permissions(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页项数"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    module: Optional[str] = Query(None, description="按模块过滤")
):
    """
    获取权限列表，支持分页、搜索和按模块过滤
    
    Args:
        page: 页码
        page_size: 每页大小
        search: 搜索关键词
        module: 按模块过滤
        
    Returns:
        包含权限列表的响应
    """
    permissions, total = await PermissionService.list_permissions(page, page_size, search, module)
    
    # 计算总页数
    pages = (total + page_size - 1) // page_size if total > 0 else 1
    
    # 构造响应
    response_data = {
        "items": [PermissionResponse.model_validate(permission) for permission in permissions],
        "total": total,
        "page": page,
        "page_size": page_size,
        "pages": pages
    }
    
    return ApiResponse.success(data=response_data)


@router.get("/modules/list", summary="获取权限模块列表")
async def get_permission_modules():
    """
    获取所有权限模块名称列表
    
    Returns:
        包含权限模块名称的响应
    """
    modules = await PermissionService.get_modules()
    return ApiResponse.success(data=modules)


@router.get("/{permission_id}", summary="获取权限详情")
async def get_permission(
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    通过ID获取权限详情
    
    Args:
        permission_id: 权限ID
        
    Returns:
        包含权限信息的响应
    """
    permission = await PermissionService.get_permission_by_id(permission_id)
    return ApiResponse.success(
        data=PermissionResponse.model_validate(permission)
    )


@router.put("/{permission_id}", summary="更新权限信息")
async def update_permission(
    update_data: PermissionUpdate,
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    更新权限信息(部分更新)
    
    Args:
        update_data: 更新数据
        permission_id: 权限ID
        
    Returns:
        包含更新后权限信息的响应
    """
    # 过滤掉None值字段，只更新提供了值的字段
    update_dict = {k: v for k, v in update_data.model_dump().items() if v is not None}
    
    if not update_dict:
        return ApiResponse.success(
            msg="没有提供需要更新的字段",
            data=None
        )
    
    updated_permission = await PermissionService.update_permission(permission_id, update_dict)
    return ApiResponse.success(
        data=PermissionResponse.model_validate(updated_permission),
        msg="权限更新成功"
    )


@router.put("/{permission_id}/whole", summary="全量更新权限信息")
async def update_permission_whole(
    update_data: PermissionWholeUpdate,
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    全量更新权限信息
    
    Args:
        update_data: 完整的更新数据
        permission_id: 权限ID
        
    Returns:
        包含更新后权限信息的响应
    """
    updated_permission = await PermissionService.update_permission_whole(
        permission_id, update_data.model_dump()
    )
    return ApiResponse.success(
        data=PermissionResponse.model_validate(updated_permission),
        msg="权限更新成功"
    )


@router.delete("/{permission_id}", summary="软删除权限")
async def delete_permission(
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    软删除权限(逻辑删除)
    
    Args:
        permission_id: 权限ID
        
    Returns:
        删除操作的结果响应
    """
    await PermissionService.delete_permission(permission_id)
    return ApiResponse.success(msg=f"权限ID {permission_id} 已成功删除")


@router.delete("/{permission_id}/true", summary="硬删除权限")
async def hard_delete_permission(
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    硬删除权限(物理删除)
    
    Args:
        permission_id: 权限ID
        
    Returns:
        删除操作的结果响应
    """
    await PermissionService.hard_delete_permission(permission_id)
    return ApiResponse.success(msg=f"权限ID {permission_id} 已被永久删除")


@router.get("/{permission_id}/roles", summary="获取拥有权限的角色列表")
async def get_permission_roles(
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    获取拥有指定权限的所有角色
    
    Args:
        permission_id: 权限ID
        
    Returns:
        包含角色列表的响应
    """
    roles = await PermissionService.get_permission_roles(permission_id)
    return ApiResponse.success(
        data=[{"id": role.id, "name": role.name, "slug": role.slug} for role in roles]
    )


@router.get("/{permission_id}/users", summary="获取拥有权限的用户列表")
async def get_permission_users(
    permission_id: int = Path(..., ge=1, description="权限ID")
):
    """
    获取直接拥有指定权限的所有用户
    
    Args:
        permission_id: 权限ID
        
    Returns:
        包含用户列表的响应
    """
    users = await PermissionService.get_permission_users(permission_id)
    return ApiResponse.success(
        data=[{"id": user.id, "username": user.username} for user in users]
    )


@router.post("/{permission_id}/users/{user_id}", summary="为用户分配权限")
async def assign_permission_to_user(
    permission_id: int = Path(..., ge=1, description="权限ID"),
    user_id: int = Path(..., ge=1, description="用户ID")
):
    """
    为用户分配直接权限
    
    Args:
        permission_id: 权限ID
        user_id: 用户ID
        
    Returns:
        操作结果响应
    """
    success = await PermissionService.assign_permission_to_user(permission_id, user_id)
    
    if success:
        return ApiResponse.success(msg="权限分配成功")
    else:
        return ApiResponse.success(msg="权限已存在，无需重复分配")


@router.delete("/{permission_id}/users/{user_id}", summary="移除用户权限")
async def remove_permission_from_user(
    permission_id: int = Path(..., ge=1, description="权限ID"),
    user_id: int = Path(..., ge=1, description="用户ID")
):
    """
    移除用户的直接权限
    
    Args:
        permission_id: 权限ID
        user_id: 用户ID
        
    Returns:
        操作结果响应
    """
    success = await PermissionService.remove_permission_from_user(permission_id, user_id)
    
    if success:
        return ApiResponse.success(msg="权限移除成功")
    else:
        return ApiResponse.success(msg="权限不存在，无需移除")
